package com.itheima.controller;

import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.service.impl.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.itheima.controller.Code.*;

/**
 * @author tongchen
 * @create 2022-12-12 11:06
 */
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean save = bookService.save(book);
        return new Result(save==false?SAVE_ERR:SAVE_OK,save);
    }
@PutMapping
    public Result update(@RequestBody Book book) {
    boolean update = bookService.update(book);
    return new Result(update==false?UPDATE_ERR:UPDATE_OK,update);
    }
@DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
    boolean delete = bookService.delete(id);
    return new Result(delete==false?DELETE_ERR:DELETE_OK,delete);

    }
@GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
    Book service = bookService.getById(id);
    Integer code = service != null ? Code.GET_OK : Code.GET_ERR;
    String msg = service != null ? "" : "数据查询失败，请重试！";
    return new Result(code,service,msg);
    }
@GetMapping
    public Result getAll() {
    List<Book> all = bookService.getAll();
    Integer code = all != null ? Code.GET_OK : Code.GET_ERR;
    String msg = all != null ? "" : "数据查询失败，请重试！";
    return new Result(code,all,msg);
}
}
